/*
 * Copyright 2012 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.ekuma.android.ui.scan.history;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import cn.ekuma.android.keyBoardinput.KeyBoradInputPanel;
import cn.ekuma.android.ui.InputView;
import cn.ekuma.android.ui.InputView.OnSelectedActionListener;
import cn.ekuma.android.ui.scan.history.upload.LocalHistoryActivity;
import cn.ekuma.epos.android.Config;
import cn.ekuma.epos.ui.android.R;

import com.android.calculator2.Logic.OnReturnListener;
import com.openbravo.bean.pda.LocalHistory;
import java.util.Date;
import java.util.List;

public final class HistoryActivity extends ListActivity {

  private static final int SEND_ID = Menu.FIRST;
  private static final int CLEAR_ID = Menu.FIRST + 1;
  private static final int LOCALHISTORY_ID = Menu.FIRST + 2;
  private static final int EXPORT_ID = Menu.FIRST + 3;


  private HistoryManager historyManager;
  private HistoryItemAdapter adapter;
  private String localMachineName;
  protected SharedPreferences prefs;
   private int exprotType;

  @Override
  protected void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    localMachineName=prefs.getString(Config.KEY_LOCAL_MACHINE_NAME,"pad");
    exprotType=Integer.parseInt(prefs.getString(Config.KEY_EXPORT_TYPE, "0"));
    historyManager = new HistoryManager(this);
    adapter = new HistoryItemAdapter(this);
    setListAdapter(adapter);
    ListView listview = getListView();
    registerForContextMenu(listview);
    getActionBar().setDisplayHomeAsUpEnabled(true);
  }

  @Override
  protected void onResume() {
    super.onResume();
    List<HistoryItem> items = historyManager.buildHistoryItems();
    adapter.clear();
    for (HistoryItem item : items) {
      adapter.add(item);
    }
    if (adapter.isEmpty()) {
      adapter.add(new HistoryItem(null, null, null,0));
    }
  }

  @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
    if (adapter.getItem(position).getResult() != null) {
    	final HistoryItem selectItem=adapter.getItem(position);
        AlertDialog.Builder builder = new AlertDialog.Builder(HistoryActivity.this);
    	KeyBoradInputPanel inputView=new KeyBoradInputPanel(HistoryActivity.this);
        builder.setView(inputView);
        final AlertDialog dialog=builder.create();
        inputView.setInputListener(new OnReturnListener(){
			public void onReturn(String value) {
				   double retValue=0;
				   if(value!=null&&value.length()>0){
		              retValue=Double.valueOf(value);
				   historyManager.updateHistoryItemUnits(selectItem.getResult().getText(), retValue);
				   selectItem.setUnits(retValue);
				   adapter.notifyDataSetChanged();
				}
				dialog.dismiss();	
			}

			public void onCommand(int command,String value) {
				onReturn(value);
			}
        }); 
        inputView.reset(selectItem.getUnits());
        dialog.show();  
    }
  }

  @Override
  public void onCreateContextMenu(ContextMenu menu,
                                  View v,
                                  ContextMenu.ContextMenuInfo menuInfo) {
    int position = ((AdapterView.AdapterContextMenuInfo) menuInfo).position;
    menu.add(Menu.NONE, position, position, R.string.history_clear_one_history_text);
  }

  @Override
  public boolean onContextItemSelected(MenuItem item) {
    int position = item.getItemId();
    historyManager.deleteHistoryItem(position);
    adapter.remove(adapter.getItem(position));
    adapter.notifyDataSetChanged();
    return true;
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    if (historyManager.hasHistoryItems()) {
        menu.add(0, EXPORT_ID, 0, R.string.history_export).setIcon(android.R.drawable.ic_menu_save);
        menu.add(0, CLEAR_ID, 0, R.string.history_clear_text).setIcon(android.R.drawable.ic_menu_delete);
        menu.add(0, SEND_ID, 0, R.string.history_save).setIcon(android.R.drawable.ic_menu_share);
    }
    menu.add(0, LOCALHISTORY_ID, 0, R.string.localhistory).setIcon(android.R.drawable.btn_star);
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case SEND_ID:
        CharSequence history = historyManager.buildHistory(HistoryManager.EXPORT_STYLE_CODE_UNIT_NAME);
        if(history.length()>0){
            LocalHistory entry=new LocalHistory();
            Date createDate=new Date();
            entry.setId(String.valueOf(createDate.getTime()));
            entry.setCreateDate(createDate);
            entry.setCsvValue(history.toString());
            entry.setLocalMachineName(localMachineName);
            entry.setCsvMore(historyManager.buildHistory(HistoryManager.EXPORT_STYLE_CODE_UNIT).toString());
            historyManager.saveLocalHistory(entry);   
        }
        break;
      case CLEAR_ID:
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.msg_sure);
        builder.setCancelable(true);
        builder.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int i2) {
            historyManager.clearHistory();
            dialog.dismiss();
            adapter.clear();
            adapter.add(new HistoryItem(null, null, null,0));
            adapter.notifyDataSetChanged();
          }
        });
        builder.setNegativeButton(R.string.button_cancel, null);
        builder.show();
        break;
      case LOCALHISTORY_ID:
    	  Intent intent = new Intent(Intent.ACTION_VIEW);
          intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
          intent.setClassName(this, LocalHistoryActivity.class.getName());
          startActivity(intent);
          break;
        case EXPORT_ID:
                 CharSequence history1 = historyManager.buildHistory(exprotType);
                 Uri historyFile = HistoryManager.saveHistory(history1.toString());
                 if (historyFile == null) {
                     AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
                     builder1.setMessage(R.string.msg_unmount_usb);
                     builder1.setPositiveButton(R.string.button_ok, null);
                     builder1.show();
                 }else{
                     AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
                     builder1.setMessage("以保存在:"+historyFile.getPath());
                     builder1.setPositiveButton(R.string.button_ok, null);
                     builder1.show();
                 }
            break;
       case android.R.id.home:
                    finish();
                    return true;
    default:
        return super.onOptionsItemSelected(item);
    }
    return true;
  }

}
